package com.sojson.config.log;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sojson.config.task.bean.TdHandler;
import com.sojson.util.ThreadLocalUtil;
import com.sojson.util.log.LogUtil;

/**
 * 日志配置类
 *
 * @author liu
 * @date 2020-11-02
 */
@Configuration
public class LogConfig {

    /**
     * 线程装饰器,类似切面
     *
     * @return
     */
    @Bean
    public TdHandler<String> logTdHandler() {
        // 线程
        TdHandler<String> handler = new TdHandler<String>() {
            @Override
            public String prefix() {
                return LogUtil.getTraceId();
            }

            @Override
            public void runByThread(Object obj) {
                LogUtil.setTraceId(Thread.currentThread().getName() + "-" + obj);
            }

            @Override
            public void finallys() {
                LogUtil.clearTraceId();
            }

            @Override
            public int getSort() {
                return 0;
            }
        };
        // 过滤器
        ThreadLocalUtil.addHandler(new TdHandler<String>() {

            @Override
            public void run() {
                LogUtil.setTraceId();
            }

            @Override
            public void runByTask() {
                LogUtil.setTraceId(Thread.currentThread().getName() + "-" + LogUtil.creTraceId());
            }

            @Override
            public void finallys() {
                LogUtil.clearTraceId();
            }

            @Override
            public int getSort() {
                return 0;
            }
        });
        return handler;
    }

}